package dasregistry.security;

import org.biojava.services.das.dao.AuthenticationDAO;
import org.junit.After;
import org.springframework.beans.factory.BeanFactory;




public class Authenticate {

	CryptoUtils crypt;
	AuthenticationDAO auth;
	
	public AuthenticationDAO getAuth() {
		return auth;
	}
	public void setAuth(AuthenticationDAO auth) {
		this.auth = auth;
	}
	public Authenticate(){
		crypt=new CryptoUtils();
	}
	/**
	 * if the email returned is not "" then we have a authenticated user
	 * @param username
	 * @param password
	 * @return
	 */
	public boolean authenticate(String username, String password){
		// username="jw12@sanger.ac.uk";
		String userPass=crypt.getDigestString(password);
		
		String databasePass=this.getPassFromDatabase(username);
		//if empty string something went wrong so return false
		if(databasePass.equals(""))
			{
			System.out.println("databasePass in authenticate method pass is empty string "+userPass+"="+databasePass);
			return false;
			}
		if(userPass.equals(databasePass)){
			System.out.println("user pass=database pass "+userPass+"="+databasePass );
			return true;
		}else{
			System.out.println("user pass does not equal databasePass"+userPass+"="+databasePass);
			return false;
		}
		
	}
	private String getPassFromDatabase(String username) {
		//get encrypted pass from database and return String representation
		return auth.getEncryptedPass(username);
		
	}
	
	public String addUserWithPass(String username, String unencryptedPassword, String dislayName, int role, int alertMe){
		String errorMessage="";
		//encrypte password and store in database
		String encryptedPassword=crypt.getDigestString(unencryptedPassword);
		
		errorMessage=auth.addUserWithPass(username, dislayName, encryptedPassword, role, alertMe);
		
		return errorMessage;
	}
	
	public String removeUser(String email) {
		String errors=auth.deleteUser(email);
		return errors;
	}
	
	public boolean userExists(String email){
		return auth.userExists(email);
	
	}
	public String updatePassword(String email, String pass) {
		String errorMessage="";
		//encrypte password and store in database
		String encryptedPassword=crypt.getDigestString(pass);
		System.out.println("calling update pass in authenticate with "+encryptedPassword);
		errorMessage=auth.updatePass(email ,encryptedPassword);
		
		return errorMessage;
	}
}
